package com.twetec.cms.common.util.file;


import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.file.FileWriter;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

public class LocalFileUtil{

    /**
     * 获取文件树
     */
    public static void getFileTreeListByPath(String path, File file, FileTreeItem fileTreeParentItem) {
        ArrayList<FileTreeItem> fileTreeItemList = new ArrayList<>();
        File[] fileList = file.listFiles();
        for (File childFile : fileList) {

            FileTreeItem fileTreeItem = new FileTreeItem();
            // 绝对路径
            fileTreeItem.setAbsolutePath(childFile.getAbsolutePath());
            // 相对路径
            int subStart = path.length();
            fileTreeItem.setRelativePath(childFile.getAbsolutePath().substring(subStart));
            // 文件名
            fileTreeItem.setFileName(childFile.getName());
            // 文件大小
            fileTreeItem.setSize(FileUtil.size(childFile));

            // 如果是文件
            if (childFile.isFile()) {
                // 设置属性
                fileTreeItem.setIsDir(0);
                fileTreeItem.setExt(FileUtil.getSuffix(childFile));

            }
            // 如果是目录
            if (childFile.isDirectory()) {
                fileTreeItem.setIsDir(1);
                // 如果不是空目录
                if (!FileUtil.isDirEmpty(childFile)) {
                    fileTreeItem.setSize(FileUtil.size(childFile));
                    getFileTreeListByPath(path, childFile, fileTreeItem);
                }
            }
            // 添加到集合
            fileTreeItemList.add(fileTreeItem);
        }
        // 遍历完成这个目录以后
        fileTreeParentItem.setChildList(fileTreeItemList);

    }

    /**
     * 创建目录
     */
    public static boolean createDir(String path, String dirName) {
        // 判断目录是否存在
        String dirPath = path + File.separator + dirName;
        if (FileUtil.exist(dirPath)) {
            return false;
        }
        File file = FileUtil.file(path + File.separator + dirName);
        return file.mkdir();
    }

    /**
     * 删除目录
     */
    public static boolean deleteDir(String pathName) {
        // 判断目录是否存在
        if (!FileUtil.exist(pathName)) {
            return true;
        }
        File file = FileUtil.file(pathName);

        // 目录为空才能删除
        if (!FileUtil.isDirEmpty(file)) {
            return false;
        }

        return FileUtil.del(file);
    }

    /**
     * 创建文件
     */
    public static boolean createFile(String path, String fileName) {
        // 判断是否存在
        String filePath = path + File.separator + fileName;
        if (FileUtil.exist(filePath)) {
            return false;
        }

        File file = FileUtil.file(filePath);
        File touch = FileUtil.touch(file);
        return true;
    }

    /**
     * 删除文件
     */
    public static boolean deleteFile(String pathName) {

        // 如果文件不存在
        if (!FileUtil.exist(pathName)) {
            return false;
        }
        return FileUtil.del(pathName);
    }


    /**
     * 编辑文件内容
     */
    public static boolean setFileContent(String path, String content) throws IOException {
        File file = FileUtil.file(path);
        // 缓冲流，输出文件时不做追加，只做覆盖
        BufferedWriter bufferedWriter = FileUtil.getWriter(file, Charset.defaultCharset(), false);
        bufferedWriter.write(content);
        bufferedWriter.flush();
        bufferedWriter.close();
        return true;
    }

    /**
     * 获取文件内容
     */
    public static StringBuffer  getFileContent(String path) throws IOException {
        BufferedReader bufferedReader = FileUtil.getUtf8Reader(path);
        StringBuffer fileContent = new StringBuffer();
        char[] chars = new char[1024];
        int length ;
        while ((length = bufferedReader.read(chars)) != -1) {
            String fileString = new String(chars, 0, length);
            fileContent.append(fileString);
        }
        bufferedReader.close();
        return fileContent;
    }

    /**
     * 下载文件
     */
    public static File  downloadFile(String filePath,HttpServletResponse response) throws IOException {
        File file = new File(filePath);
        if(file.exists()){
            InputStream in = null;
            OutputStream out = null;
            response.setCharacterEncoding("UTF-8");
            response.setHeader("content-disposition","attachment;fileName="+file.getName());
            response.setHeader("FileName", file.getName());
            response.setHeader("Access-Control-Expose-Headers", "FileName");
            try {
                out=  response.getOutputStream();
                in = new FileInputStream(file);
                byte[] buffer  = new byte[1024];
                int i=in.read(buffer );
                while (i!=-1){
                    out.write(buffer , 0, i);// 将缓冲区的数据输出到浏览器
                    i= in.read(buffer );
                }
            } catch (IOException e) {
                throw e;
            }finally {
                in.close();
                out.close();
            }
        }
        return file;
    }

    /**
     * 上传文件
     */
    public static boolean uploadFileContent(String path, MultipartFile file) throws IOException {
        String fileName = file.getOriginalFilename();
//        String suffix = FileUtil.getSuffix(fileName);
        File importFile = FileUtil.file(path + File.separator + fileName);
        InputStream inputStream = file.getInputStream();
        FileUtil.writeFromStream(inputStream, importFile);
        inputStream.close();
        return true;
    }

    /**
     * 是否为文件
     * @param path
     * @return
     */
    private static boolean isFile(String path){
        boolean isLegal = FileUtil.exist(path) && FileUtil.isFile(path);
        return isLegal;
    }

    /**
     * 是否为目录
     * @param path
     * @return
     */
    private static boolean isDirectory(String path){
        boolean isLegal = FileUtil.exist(path) && FileUtil.isDirectory(path) && StringUtils.isNotBlank(path);
        return isLegal;
    }
}
